<template>
  <div class="list-container" v-loading.fullscreen.lock="loading">
    <div ref="tableHeaderContainer" class="bg-w list-search-group-container" style="display: block">
      <form class="task-flex task-ai" onsubmit="return false;">
        <div class="base-search-group input-with-append-search task-flex task-ai">
          <el-input v-model="searchModel.keyWord" :placeholder="$t('member.exchangeRule.title5')" class="task-with-input task-mr12">
            <i slot="prefix" class="el-input__icon el-icon-search"></i>

            <el-button
              type="primary"
              slot="append"
              @click="
                searchModel.pageNum = 1;
                handleSearch();
              "
              native-type="submit"
            >
              {{ $t('common.base.search') }}
            </el-button>
          </el-input>
          <el-button type="plain-third" @click="resetParams">{{ $t('common.base.reset') }}</el-button>
        </div>
      </form>

      <div class="header-nav">
        <div class="filter-item">
          <div class="task-font14 task-c7 state">{{ $t('common.member.exchangeType')}}：</div>
          <div class="list list-crate">
            <div class="list-item task-flex task-ai">
              <div
                v-for="(item, index) in selectStateList"
                :key="index"
                class="task-nav-create"
                :class="{
                  'task-c2': selectState === item.exchangeType,
                  'task-padding-0': selectState === item.exchangeType,
                }"
                @click.stop="handleStateChange(item.exchangeType)"
              >
                <span class="actived" style="maring: 0 12px 8px 0; display: inline-block;">
                  {{ item.exchangeType ? `${item.exchangeTypeDesc}(${item.count})` : item.exchangeTypeDesc }}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="list-section">
      <div ref="tableDoContainer" class="operation-bar-container">
        <!-- 按钮区域 -->
        <div class="top-btn-group flex-x">
          <el-dropdown @command="handleSetRules">
            <el-button type="primary" v-if="editPermission"> 
              <i class="iconfont icon-add2"></i> 
              {{ $t('common.member.exchangeRules')}} 
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="3" v-if="partsVersion">{{ $t('common.form.type.material') }}</el-dropdown-item>
              <el-dropdown-item command="1" v-else>{{ $t('common.base.sparePart') }}</el-dropdown-item>
              <el-dropdown-item command="2">{{ $t('common.fields.serviceName.displayName') }}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

          <el-button v-if="editPermission" type="plain-third" @click="handleEdit(true)"> 
            <i class="iconfont icon-edit-square"></i>
            {{ $t('common.base.bulkEdit') }} 
          </el-button>

          <el-button v-if="editPermission" type="plain-third" @click="handleDelete(true)"> 
            <i class="iconfont icon-delete"></i>
            {{ $t('common.base.delete') }} 
          </el-button>
        </div>

        <!-- 更多操作区域 -->
        <div class="action-button-group flex-x bg-w">
          <el-dropdown trigger="click">
            <div class="task-ai task-flex task-font14 task-c6 cur-point bg-w">
              <span class="task-mr4 task-ml4">{{ $t('common.base.moreOperator') }}</span>
              <i class="iconfont icon-fdn-select"></i>
            </div>
            <el-dropdown-menu slot="dropdown">
              <template v-if="exportImportPermission">
                <el-dropdown-item>
                  <div @click="handleExport(false)">{{ $t('common.base.export') }}</div>
                </el-dropdown-item>
                <el-dropdown-item>
                  <div @click="handleExport(true)">{{$t('common.base.exportAll')}}</div>
                </el-dropdown-item>
              </template>
            </el-dropdown-menu>
          </el-dropdown>

          <!-- 选择列 -->
          <div class="guide-box">
            <div class="task-ai task-flex task-font14 columns cur-point task-width103" @click="handleOpenSelectColumn">
              <span class="task-mr4">{{ $t('common.base.choiceCol') }}</span>
              <i class="iconfont icon-fdn-select"></i>
            </div>
          </div>
        </div>
      </div>

      <div class="bg-w pad-l-16 pad-r-16">
        <el-table 
          v-table-style
          stripe 
          :data="page.list" 
          :highlight-current-row="false" 
          :key="tableKey" 
          :row-key="getRowKey" 
          :border="true" 
          @select="handleSelection" 
          @select-all="handleSelection" 
          @header-dragend="headerDragend" 
          class="task-list-table common-list-table bg-w bbx-normal-list-box list-table" 
          header-row-class-name="common-list-table-header taks-list-table-header" 
          :height="tableContainerHeight" 
          ref="multipleTable"
        >
          <template slot="empty">
            <BaseListForNoData v-show="!loading" :notice-msg="$t('common.base.noData')"></BaseListForNoData>
          </template>
          <el-table-column type="selection" align="center"></el-table-column>
          <template v-for="(column, index) in columns">
            <el-table-column 
              v-if="column.show" 
              :key="`${column.field}_${index}`" 
              :label="column.label" 
              :prop="column.field" 
              :width="column.width" 
              :min-width="column.minWidth || '120px'" 
              :sortable="column.sortable" 
              :fixed="column.fixLeft || false" 
              :align="column.align" 
              show-overflow-tooltip
            > 
              <template slot-scope="scope">
                <!-- 编号 -->
                <template v-if="column.field === 'objectNo'">
                  <a
                    href=""
                    class="view-detail-btn"
                    v-if="scope.row.objectNo"
                    @click.stop.prevent="handleOpenMenuTab(scope.row)"
                  >
                    {{ scope.row.objectNo }}
                  </a>
                </template>
                <!-- 商品图片 -->
                <template v-else-if="column.field === 'objectAttachment'">
                  <el-image
                    v-if="getUrl(scope.row.objectAttachment)"
                    :src="getUrl(scope.row.objectAttachment)"
                    class="view-image"
                    @click.stop="
                      previewImg(
                        getUrl(scope.row.objectAttachment),
                        scope.row.objectAttachment
                      )
                    "
                  ></el-image>
                </template>
                <!-- 商品类型 -->
                <template v-else-if="column.field === 'objectType'">
                  {{ getOriginType(scope.row.objectType) }}
                </template>
                <!-- 兑换规则 -->
                <template v-else-if="column.field === 'exchangeType'">
                  {{ scope.row.exchangeTypeDesc }}
                </template>
                <!-- 价格 -->
                <template v-else-if="column.field === 'objectPrice'">
                  {{ numFilter(scope.row.objectPrice) || 0 }}
                </template>
                <template v-else>
                  {{ $formatFormField(column, scope.row) }}
                </template>
              </template>
            </el-table-column>
          </template>
          <el-table-column fixed="right" :label="$t('common.base.operation')" width="120">
            <template slot-scope="scope">
              <el-button 
                v-if="editPermission"
                @click.native.prevent="handleEdit(false, scope.row)" 
                type="text" 
                size="small"
              >
                {{ $t('common.base.edit') }}
              </el-button>
              <el-button 
                v-if="editPermission"
                @click.native.prevent="handleDelete(false, scope.row)" 
                type="text"
                size="small"
              >
                {{ $t('common.base.delete') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页区域 -->
      <div ref="tableFooterContainer" class="table-footer bbx-normal-table-footer-10">
        <div class="list-info">
          {{ $t('goods.list.total') }}
          <span class="level-padding">{{ page.totalElements }}</span>
          {{ $t('common.base.piece') }}
        </div>
        <el-pagination 
          class="product-table-pagination" 
          background 
          @current-change="handleCurrentChange" 
          @size-change="handleSizeChange" 
          :page-sizes="[10, 20, 50]" 
          :page-size="page.pageSize" 
          :current-page="page.pageNum" 
          layout="prev, pager, next, sizes, jumper" 
          :total="page.totalElements"> 
        </el-pagination>
      </div>
    </div>

    <!-- 商品发布弹窗 -->
    <GoodsReleasedDialog ref="goodsReleasedRef" :is-released="false" @setRules="openSetRulesDialog" />
    <!-- 设置兑换规则 -->
    <SetExchangeRuleDialog ref="setExchangeRuleRef" :member-auth="memberAuth" @reloadPage="reloadPage" />

    <!-- 选择列弹窗 -->
    <biz-select-column 
      ref="selectColumnRef" 
      mode="exchangeRule" 
      :sotrage-key="'exchangeRule_select_column'" 
      @save="saveColumnStatus" 
    />

    <!-- 导出弹窗 -->
    <base-export-group
      ref="exportPanelRef"
      :alert="exportAlert"
      :columns="exportColumns"
      :build-params="buildExportParams"
      :group="true"
      :validate="checkExportCount"
      :needchoose-break="false"
      method="post"
      :action="exchangeRuleExport"
      :is-show-export-tip="isOpenData"
    />
  </div>
</template>

<script>
import _ from 'lodash';
import Page from '@model/Page';
import i18n from '@src/locales';
import { getRootWindow } from '@src/util/dom';
import { formatDate } from '@src/util/lang';
import { safeNewDate } from '@src/util/time';
import { getOssUrl } from '@src/util/assets'
import { isOpenData, openAccurateTab } from '@src/util/platform';
import { storageGet, storageSet } from '@src/util/storageV2';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum';
import { exchangeRuleFields } from '@src/modules/member/field.js';
import GoodsReleasedDialog from '@src/modules/linkc/goods/components/GoodsReleasedDialog.vue';
import SetExchangeRuleDialog from '@src/modules/member/exchangeRule/components/SetExchangeRuleDialog.vue';
import { 
  getExchangeType, 
  getExchangeRuleList, 
  deleteExchangeRule,
  getPointsAndServiceFeeEnable,
} from '@src/api/Member'
import { exchangeRuleExport } from '@src/api/Export';
import AuthUtil from '@src/util/auth';
import AuthMixin from '@src/mixins/authMixin';
import AuthEnum from '@model/enum/AuthEnum.ts';
const goodsDefault = getOssUrl('/goodsDefault.png');

export default {
  mixins: [AuthMixin],
  components: {
    GoodsReleasedDialog,
    SetExchangeRuleDialog,
  },
  data() {
    return {
      loading: false,
      page: new Page(),
      searchModel: {
        keyWord: '',
        pageSize: 10,
        pageNum: 1,
        exchangeType: '', // 状态
      },
      selectState: '',
      // 头部筛选列表
      selectStateList: [],
      columns: [],
      tableKey: (Math.random() * 1000) >> 2,
      tableContainerHeight: '440px',
      selectedLimit: 500,
      multipleSelection: [],
      multipleSelectionPanelShow: false,
      exchangeRuleExport,
      isOpenData,
      exchangeRuleFields,
      memberAuth: {},
      exchangeTypeLang: {
        3: i18n.t('member.list.title15'),
        4: i18n.t('member.list.title16'),
        5: i18n.t('member.list.title22'),
        6: i18n.t('member.list.title23')
      }
    };
  },
  computed: {
    // 备件版本，灰度开启取备件3.0即物料，没有开启取备件2.0
    partsVersion() {
      const RootWindow = getRootWindow(window);
      return RootWindow?.grayAuth?.cloudwarehouse ?? true;
    },
    getRowKey(row) {
      return row.id || '';
    },
    exportColumns() {
      const exportColumns = this.exchangeRuleFields?.filter(v => v.export);
      exportColumns.forEach(v => {
        v.label = v.displayName;
        v.exportAlias = v.fieldName;
      });

      let arr = [
        {
          label: i18n.t('member.exchangeRule.title6'),
          value: 'exchangeRuleExport',
          columns: exportColumns,
        },
      ];
      return arr;
    },
    selectedIds() {
      return this.multipleSelection.map(v => v.id) || [];
    },
    editPermission() {
      return AuthUtil.hasAuth(this.globalLoginUserAuth, AuthEnum.MEMBER_RULE_EDIT);
    },
    exportImportPermission() {
      return AuthUtil.hasAuth(this.globalLoginUserAuth, AuthEnum.MEMBER_RULE_EXPORT);
    },
  },
  mounted() {
    this.handleReloadPage();
    // this.getTypeList();

    let that_ = this;
    // 监听切换后需要重新计算列表高度
    window.addEventListener('message', event => {
      const { action, data } = event.data;
      if (action == 'shb.frame.activatedPage') {
        that_.$nextTick(() => {
          that_.knowTableContainerHeight();
        });
      }
    });
    this.$nextTick(() => {
      this.knowTableContainerHeight();
      window.onresize = _.debounce(() => {
        that_.knowTableContainerHeight();
      }, 500);
    });
  },
  methods: {
    handleReloadPage() {
      this.buildColumns();
      // 统计兑换规则类型数据
      this.getExchangeType();
      // 获取权限
      this.getMemberAuth();
      this.handleSearch();
    },
    async getExchangeType() {
      try {
        const { code, result, message } = await getExchangeType({});

        if (code !== 0) {
          this.$message.error(message || this.$t('member.exchangeRule.title8'));
        } else {
          
          // 3 积分兑换 4 服务费兑换 5 金额+积分 6 金额+服务费
          this.selectStateList = (result || []).map(item => {
            return {
              exchangeType: item.exchangeType,
              count: item.count,
              exchangeTypeDesc: this.exchangeTypeLang[item.exchangeType] || item.exchangeTypeDesc
            }
          });
        }

        this.selectStateList?.unshift({
          exchangeType: '',
          exchangeTypeDesc: this.$t('common.base.all'),
        })
      } catch (error) {
        console.error('getExchangeType', error);
      }
    },
    async getMemberAuth() {
      try {
        const { status, data, message } = await getPointsAndServiceFeeEnable({});

        if (status !== 0) this.$message.error(message || this.$t('member.exchangeRule.title9'));
        
        this.memberAuth = data;
      } catch (error) {
        console.error('getMemberAuth', error);
      }
    },
    async handleSearch() {
      try {
        this.loading = true;

        const { code, result } = await getExchangeRuleList(this.searchModel);

        if (code !== 0) {
          this.loading = false;
          this.page = this.$options.data.call(this).page;
          return this.$message.error(this.$t('goods.tips.queryListFailed'));
        }

        const { pageNum, list, total, pageSize } = result;
        [
          this.page['list'],
          this.page['totalElements'],
          this.page['pageNum'],
          this.page['pageSize'],
        ] = [list, total, pageNum, pageSize];

        this.loading = false;
      } catch (error) {
        this.loading = false;
        console.error('fetch goods list error', error);
      }
    },
    resetParams() {
      const option = this.$options.data.call(this);
      this.searchModel = option.searchModel;
      this.selectState = option.selectState;
      this.page = option.page;

      this.handleSearch();
    },
    reloadPage() {
      this.$refs.goodsReleasedRef?.close();

      this.multipleSelection = [];
      this.$refs.multipleTable.clearSelection();
      this.getExchangeType();
      this.handleSearch();
    },
    // 构建列表表头
    buildColumns() {
      const localStorageData = this.getLocalStorageData();
      let columnStatus = localStorageData.columnStatus || [];

      let localColumns = columnStatus
        .map(i => (typeof i == 'string' ? { field: i, show: true } : i))
        .reduce((acc, col, currentIndex) => {
          acc[col.field] = {
            field: col,
            index: currentIndex,
          };
          return acc;
        }, {});

      let fields = [...this.exchangeRuleFields].sort((a, b) => a.orderId - b.orderId);
      if (Array.isArray(columnStatus) && columnStatus.length > 0) {
        fields = this.buildSortFields(fields, localColumns);
      }

      this.columns = fields
        .map(field => {
          let sortable = false;
          let minWidth = null;

          if (field.displayName.length > 4) {
            minWidth = field.displayName.length * 20;
          }

          if (field.fieldName === 'objectNo') minWidth = 200;
          if (field.formType === 'datetime' || ['exchangeType', 'ruleDesc'].includes(field.fieldName)) {
            minWidth = 160
          };

          return {
            ...field,
            label: field.displayName,
            field: field.fieldName,
            formType: field.formType,
            minWidth: typeof minWidth == 'number' ? minWidth : `${minWidth}px`,
            sortable,
            isSystem: field.isSystem,
          };
        })
        .map(col => {
          let show = col.show === true;
          let { width } = col;
          let localField = (localColumns[col.field] && localColumns[col.field].field) || null;

          let fixLeft = localField?.fixLeft || null;

          if (null != localField) {
            width = typeof localField.width == 'number' ? `${localField.width}px` : `${localField.width}`.indexOf('px') ? localField.width : '';
            show = localField.show !== false;
          }

          col.show = show;
          col.width = width;
          col.type = 'column';
          col['fixLeft'] = fixLeft && 'left';
          return col;
        });
    },
    buildSortFields(originFields = [], fieldsMap = {}) {
      let fields = [];
      let unsortedFields = [];

      originFields.forEach(originField => {
        let { fieldName } = originField;
        let field = fieldsMap[fieldName];

        if (field) {
          let { index } = field;
          fields[index] = originField;
        } else {
          unsortedFields.push(originField);
        }
      });

      // 存储列数据之后，如果存在列被删除的情况，可能产生空值，需要过滤，否则其他地方没做判断会报错
      return fields.filter(v => v).concat(unsortedFields);
    },
    async handleDelete(isBatch, row) {
      if (isBatch && !this.multipleSelection.length) {
        return this.$platform.alert(i18n.t('task.tip.taskListTip2'));
      }
      
      try {
        if (!(await this.$platform.confirm(this.$t('member.exchangeRule.title10')))) return;
        this.loading = true;

        const ids = isBatch ? this.multipleSelection.map(p => p.id) : [row.id];
        const { code, message } = await deleteExchangeRule({ ruleIdList: ids });
        this.loading = false;

        if (code !== 0) {
          return this.$message.error(message || this.$t('common.base.deleteFail'));
        }
        this.$message.success(this.$t('common.base.deleteSuccess'));

        this.multipleSelection = [];
        setTimeout(() => {
          this.getExchangeType();
          this.handleSearch();
        }, 1000);
      } catch (error) {
        this.loading = false;
        console.error('error', error);
      }
    },
    handleEdit(isBatch, row = {}) {
      if (isBatch && !this.multipleSelection.length) {
        return this.$platform.alert(this.$t('member.exchangeRule.title11'));
      }

      const params = {
        ruleIdList: isBatch ? this.multipleSelection.map(p => p.id) : [row?.id]
      };
      const action = isBatch ? 'batchEdit' : 'edit';
      this.$refs.setExchangeRuleRef?.open(action, params, row);
    },
    handleSetRules(command) {
      this.$refs.goodsReleasedRef?.open(~~command);
    },
    handleStateChange(val) {
      this.selectState = val;
      this.searchModel.pageNum = 1;
      this.searchModel.exchangeType = val;
      this.handleSearch();
    },
    openSetRulesDialog(params) {
      this.$refs.setExchangeRuleRef?.open('create', params);
    },
    handleOpenSelectColumn() {
      this.$refs.selectColumnRef?.open(this.columns);
    },
    handleSelection(selection) {
      let tv = this.selectionCompute(selection);

      let original = this.multipleSelection.filter(ms => this.page.list.some(cs => cs.id === ms.id));

      let unSelected = this.page.list.filter(c => original.every(oc => oc.id !== c.id));

      if (tv.length > this.selectedLimit) {
        this.$nextTick(() => {
          original.length > 0
            ? unSelected.forEach(row => {
              this.$refs.multipleTable.toggleRowSelection(row, false);
            })
            : this.$refs.multipleTable.clearSelection();
        });
        return this.$platform.alert(this.$t('common.base.tip.maxDataCanChooseTips', { data1: this.selectedLimit }));
      }

      this.multipleSelection = tv;

      // this.$refs.baseSelectionBar?.openTooltip();
      this.$nextTick(() => {
        this.knowTableContainerHeight();
      });
    },
    selectionCompute(selection) {
      let tv = [];

      tv = this.multipleSelection.filter(ms => this.page.list.every(c => c.id !== ms.id));
      tv = _.uniqWith([...tv, ...selection], _.isEqual);

      return tv;
    },
    /**
     * @des 获取列表当前的可滚动高度
     */
    knowTableContainerHeight() {
      let min = 440;
      try {
        let window_ = window.innerHeight;
        let header = this.$refs.tableHeaderContainer?.offsetHeight || 0;
        let do_ = this.$refs.tableDoContainer?.offsetHeight || 0;
        let footer = this.$refs.tableFooterContainer?.offsetHeight || 0;
        let selection = this.$refs.BaseSelectionBarComponent?.offsetHeight || 0;
        min = window_ - header * 1 - do_ * 1 - footer * 1 - selection * 1 - 24 - 12;
        min = min > 440 ? min : 440;
      } catch (error) {
        console.warn(error, 'error try catch');
      }
      this.$set(this, 'tableContainerHeight', `${min}px`);
    },
    // 当拖动表头改变了列的宽度的时候会触发该事件
    headerDragend(newWidth, oldWidth, column, event) {
      let data = this.columns
        .map(item => {
          if (item.fieldName === column.property) {
            item.width = column.width;
          }
          return item;
        })
        .map(item => {
          return {
            field: item.field,
            show: item.show,
            width: item.width,
          };
        });
      this.modifyColumnStatus({ type: 'column', data });
    },
    /**
     * @description 修改选择列设置
     * @param {Object} event 事件对象
     */
    modifyColumnStatus(event) {
      let columns = event.data || [],
        colMap = columns.reduce((acc, col) => (acc[col.field] = col) && acc, {});
      this.columns.forEach(col => {
        let newCol = colMap[col.field];
        if (null != newCol) {
          this.$set(col, 'show', newCol.show);
          this.$set(col, 'width', newCol.width);
        }
      });

      this.saveColumnStatusToStorage();
    },
    getLocalStorageData() {  
      const dataStr = storageGet('exchangeRule_list_localStorage') || '{}';
      return JSON.parse(dataStr);
    },
    saveDataToStorage(key, value) {
      const data = this.getLocalStorageData();
      data[key] = value;
      storageSet('exchangeRule_list_localStorage', JSON.stringify(data));
    },
    /**
     * @description 修改选择列设置
     * @param {Object} event 事件对象
     */
    saveColumnStatus(event) {
      let columns = event.data || [];

      this.columns = [];

      this.$nextTick(() => {
        this.$set(this, 'columns', columns.slice());
        this.tableKey = (Math.random() * 1000) >> 2;
        this.saveColumnStatusToStorage();
      });
      this.$message.success(this.$t('common.base.saveSuccess'));
    },
    saveColumnStatusToStorage() {
      const localStorageData = this.getLocalStorageData();
      let columnsStatus = null;

      // 判断是否存储选择列
      const columnsList = this.columns.map(c => ({
        field: c.fieldName,
        show: c.show,
        width: c.width,
        fixLeft: c.fixLeft,
      }));

      if (localStorageData.columnStatus) {
        localStorageData.columnStatus = columnsList;
        columnsStatus = localStorageData.columnStatus;
      } else {
        columnsStatus = columnsList;
      }

      this.saveDataToStorage('columnStatus', columnsStatus);
    },
    handleCurrentChange(pageNum) {
      this.searchModel.pageNum = pageNum;
      this.handleSearch();
    },
    handleSizeChange(pageSize) {
      this.searchModel.pageSize = pageSize;
      this.searchModel.pageNum = 1;
      this.handleSearch();
    },
    handleExport(exportAll) {
      let ids = [];
      let fileName = `${formatDate(safeNewDate(), 'YYYY-MM-DD')}商品数据.xlsx`;
      if (!exportAll) {
        if (!this.multipleSelection.length)
          return this.$platform.alert(this.$t('common.base.tip.exportNoChoice'));
        ids = this.selectedIds;
      }
      this.$refs.exportPanelRef.open(ids, fileName);
    },
    exportAlert(result, params = {}) {
      this.$platform.alert(result.message);
    },
    /**
     * @description 构建导出参数
     * @return {Object} 导出参数
     */
    buildExportParams(checkedMap, ids, exportOneRow) {
      const { exchangeRuleExport } = checkedMap;
      const exportAll = !ids || !ids.length;

      const params = {
        checked: exchangeRuleExport.join(','),
        ids: ids.join(','),
        exportSearchModel: JSON.stringify(this.searchModel),
        dataTotal: exportAll
          ? this.page.totalElements
          : this.selectedIds.length,
      };

      return params;
    },
    /**
     * @description 检测导出条数
     * @return {String | null}
     */
    checkExportCount(ids, max) {
      let exportAll = !ids || ids.length == 0;
      return exportAll && this.page.totalElements > max
        ? this.$t('common.base.exportModal.oversizeTips', {size: '5000'})
        : null;
    },
    handleOpenMenuTab(row) {
      if (!row.id) return;

      let fromId = window.frameElement.getAttribute('id');
      const params = {
        key: row.objectId,
        // titleKey: ` - ${row.objectName}`,
        params: `id=${row.objectId}`,
        fromId,
      }

      if (row.objectType === 1) {
        params.type = PageRoutesTypeEnum.PagePartCategoryDetail;
      } else if (row.objectType === 2) {
        params.type = PageRoutesTypeEnum.PageServicePriceDetailView;
      } else {
        params.type = PageRoutesTypeEnum.PageItemsDetail;
        params.titleKey = `-${row.objectNo}`;
      }

      openAccurateTab(params);
    },
    // 截取当前数据到小数点后两位
    numFilter(value) {
      if (!value) return '';

      let tempVal = parseFloat(value).toFixed(3);
      let realVal = tempVal.substring(0, tempVal.length - 1);

      return realVal;
    },
    getUrl(arr) {
      if (Array.isArray(arr) && arr[0]?.url) return arr[0].url || '';

      // return goodsDefault;
    },
    previewImg(url, urls = []) {
      if (url === '' || url === goodsDefault) return;

      if (typeof urls !== 'object') {
        urls = [];
      }

      urls?.forEach(v => {
        v.id = v.fileId;
      });

      this.$previewElementImg(url, urls);
    },
    getOriginType(value) {
      if (!value) return '';

      if (value === 1) return this.$t('common.base.sparePart');
      if (value === 2) return this.$t('common.label.serviceItem');

      return this.$t('common.form.type.material');
    },
  },
};
</script>

<style lang="scss" scoped>
@import '@src/assets/scss/common-list.scss';

.list-container {
  height: 100%;
  padding: 10px;
  overflow: auto;

  .list-search-group-container {
    padding: 16px;
    border-radius: 3px;
  }

  form {
    justify-content: flex-end;
  }

  .header-nav {
    padding-top: 16px;
    .filter-item {
      display: flex;
      // align-items: center;
    }
    > div {
      position: relative;
      cursor: pointer;
      .state {
        padding-top: 8px;
        width: 80px;
        font-weight: 500;
        color: #8c8c8c;
      }
      .list {
        padding-right: 80px;
        flex: 1;
        overflow: hidden;
        .list-item {
          > div {
            font-size: 13px;
            max-width: 160px;
            overflow-y: hidden;
            color: #595959;
            padding: 4px 8px;
            margin: 0 12px 8px 0;
            white-space: nowrap;
            overflow: hidden;
           
          }
        }
      }
    }
  }

  .list-section {
    margin-top: 12px;
    padding-top: 0;

    .operation-bar-container {
      background: #fff;
      border-radius: 4px 4px 0 0;
      display: flex;
      justify-content: space-between;
      padding: 16px 16px 0;

      .el-dropdown-btn {
        padding: 0 15px;
        line-height: 31px;
        display: inline-block;
        background: $color-primary-light-9;
        color: $text-color-primary;
        outline: none;
        margin-left: 5px;
        .iconfont {
          margin-left: 5px;
          // font-size: 12px;
        }

        &:hover {
          cursor: pointer;
          color: #fff;
          background: $color-primary;
        }
      }
      .columns {
        color:#595959;
        &:hover {
          color: $color-primary;
        }
      }
    }
  }

  .list-table {
    .view-detail-btn {
      @include fontColor();
    }

    .view-image {
      width: 32px;
      height: 32px;
      cursor: pointer;
    }
  }

  .table-footer {
    display: flex;
    justify-content: space-between;
    padding: 0px 10px 10px 10px;
    background: #fff;
    border-radius: 0 0 3px 3px;

    .list-info {
      font-size: 13px;
      line-height: 32px;
      margin: 0;
      color: #767e89;

      .iconfont {
        position: relative;
        top: 1px;
      }

      .product-selected-count {
        color: $color-primary;
        padding: 0 3px;
        width: 15px;
        text-align: center;
        cursor: pointer;
        font-size: 13px;
      }
    }

    .el-pagination__jump {
      margin-left: 0;
    }
  }
}
</style>
